const fs = require('fs');
const path = require('path');
const exampleEnvConfig = require('./env/example');
const dev = require('./env/dev');
const test = require('./env/test');
const prod = require('./env/prod');

const ENV_PATH_MAP = { dev, test, prod };

function validateEnvConfig(example, config, targetEnvName) {
  const msg = s => `${targetEnvName}${s}`;
  if (typeof example !== typeof config) {
    return { result: false, message: msg('与示例类型不一致') };
  }
  if (!example || !config) {
    return { result: false, message: msg('或示例为空') };
  }
  const exampleKeys = Object.keys(example);
  const configKeys = Object.keys(config);

  while (exampleKeys.length) {
    const key = exampleKeys.pop();
    const index = configKeys.indexOf(key);
    if (index !== -1) {
      configKeys.splice(index, 1);
    } else {
      return { result: false, message: msg(`中的 ${key} 字段不存在`) };
    }
  }

  if (configKeys.length > 0) {
    return {
      result: false,
      message: msg(`中存在多余的字段 ${configKeys.join(',')}`)
    };
  }

  return { result: config };
}

function getNpmEnv(npmLifeCycle) {
  return npmLifeCycle.split(':');
}

function getNpmEnvTarget(npmLifeCycle) {
  const { 1: target } = getNpmEnv(npmLifeCycle);
  return target;
}

function getEnvConfig(npmLifeCycle) {
  const targetEnv = getNpmEnvTarget(npmLifeCycle);
  const envConfig = ENV_PATH_MAP[targetEnv] || ENV_PATH_MAP.dev;
  const configValidation = validateEnvConfig(
    exampleEnvConfig,
    envConfig,
    `${targetEnv} 环境文件`
  );
  if (configValidation.result) {
    return envConfig;
  }
  throw new Error(configValidation.message);
}

const [targetAction, targetEnv] = getNpmEnv(process.env.npm_lifecycle_event);

const env = {
  TARGET_ACTION: targetAction,
  TARGET_ENV: targetEnv,
  ...getEnvConfig(process.env.npm_lifecycle_event)
};

Object.keys(env).forEach(key => {
  process.env[key] = env[key];
});

function CleanJsMapPlugin() {
  function removeMapFile(root) {
    if (!fs.existsSync(root)) return;
    const stat = fs.statSync(root);
    if (stat.isFile()) {
      const filename = path.basename(root);
      if (/\.map$/.test(filename)) {
        fs.unlinkSync(root);
      }
    } else if (stat.isDirectory()) {
      const files = fs.readdirSync(root);
      files.forEach(name => removeMapFile(path.join(root, name)));
    }
  }

  this.apply = function apply(compiler) {
    compiler.hooks.afterEmit.tap('CleanJsMapPlugin', () => {
      removeMapFile(path.join(__dirname, '.nuxt'));
    });
  };
}

export default {
  env,

  server: {
    host: '0.0.0.0'
  },

  loading: true,

  head() {
    return {
      title: process.env.SITE_NAME,
      htmlAttrs: {
        lang: this.$i18n.locale
      },
      meta: [
        { charset: 'utf-8' },
        { name: 'viewport', content: 'width=device-width, initial-scale=1' }
      ],
      link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }]
    };
  },

  build: {
    transpile: ['swiper', 'ssr-window', 'dom7'],
    loaders: {
      scss: {
        sassOptions: {
          includePaths: [path.resolve('assets', 'styles')]
        }
      }
    },
    extend(config) {
      // svg
      const svgRule = config.module.rules.find(rule => rule.test.test('.svg'));
      svgRule.exclude = [path.resolve(__dirname, 'assets/svg')];
      // Includes /icons/svg for svg-sprite-loader
      config.module.rules.push({
        test: /\.svg$/,
        include: [path.resolve(__dirname, 'assets/svg')],
        loader: 'svg-sprite-loader',
        options: {
          symbolId: 'icon-[name]'
        }
      });

      // ejs
      config.module.rules.push({
        test: /\.ejs$/,
        loader: 'ejs-loader',
        options: { esModule: false, variable: 'data' }
      });
    }
  },

  css: ['@/assets/styles/common.scss'],

  modules: [
    'cookie-universal-nuxt',
    '@nuxtjs/i18n',
    ['@nuxtjs/sentry'],
    ['@nuxtjs/sitemap'],
    ...(process.env.TARGET_ACTION === 'build' ? [CleanJsMapPlugin] : [])
  ],
  sitemap: {
    hostname: 'https://www.tnaot.com/', // 你的网站域名
    gzip: true, // 生成 sitemap.xml.gz 压缩文件
    defaults: {
      changefreq: 'daily', // 默认更新频率
      priority: 0.8, // 默认优先级
      lastmod: new Date().toISOString() // 默认最后修改时间
    }
  },

  router: {
    middleware: ['i18n', 'botState']
  },

  plugins: [
    { src: '~/plugins/both' },
    { src: '~/plugins/filters' },
    { src: '~/plugins/image' },
    { src: '~/plugins/avatar' },
    { src: '~/plugins/seo' },
    { src: '~/plugins/i18n', mode: 'client' },
    { src: '~/plugins/icons', mode: 'client' },
    { src: '~/plugins/scroll', mode: 'client' },
    { src: '~/plugins/vue-lazyload', mode: 'client' }
  ],

  i18n: {
    locales: [
      { code: 'en', file: 'km-KH.js' },
      { code: 'zh', file: 'zh-Hans.js' },
      { code: 'km', file: 'km-KH.js' }
    ],
    langDir: 'lang/',
    detectBrowserLanguage: false
  },

  sentry: {
    dsn: env.SENTRY_DSN,
    config: {
      environment: env.TARGET_ENV
    },
    publishRelease: env.TARGET_ACTION === 'build' && env.TARGET_ENV !== 'dev',
    webpackConfig: {
      include: ['.nuxt/dist/'],
      deploy: {
        env: env.TARGET_ENV
      }
    }
  },

  components: true
};
